package com.lz.frame.common;

import java.util.*;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入时，自动填充 create_time 和 create_by 字段
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动填充 create_time
        if (this.getFieldValByName("createTime", metaObject) == null) {
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        }

        // 自动填充 create_by，仅当 "admin" 不为 null 时填充
        if (this.getFieldValByName("createBy", metaObject) == null) {
            String userId = "admin";
            if (userId != null && !userId.isEmpty()) {
                this.strictInsertFill(metaObject, "createBy", String.class, userId);
            }
        }
        // 自动填充 update_time
        if (this.getFieldValByName("updateTime", metaObject) == null) {
            this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        }
        // 自动填充 update_by
        if (this.getFieldValByName("updateBy", metaObject) == null) {
            String userId = "admin";
            if (userId != null && !userId.isEmpty()) {
                this.strictUpdateFill(metaObject, "updateBy", String.class, userId);
            }
        }
        //自动填充 deleted
        if (metaObject.hasSetter("deleted")) {
            setFieldValByName("deleted", Boolean.FALSE, metaObject);
        }
    }

    /**
     * 更新时，自动填充 update_time 和 update_by 字段
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 自动填充 update_time
        //下面的逻辑是错误的，因为他是判断为空才填充，但是更新之前就已经填充了，所以这里应该是判断不为空才填充
        if (metaObject.hasSetter("updateTime")) {
            setFieldValByName("updateTime", new Date(), metaObject);
        }
        if (metaObject.hasSetter("updateBy")) {
            String userId = "admin";
            if (userId != null && !userId.isEmpty()) {
                setFieldValByName("updateBy", "admin", metaObject);
            }
        }
    }
}